/*!
 @header MobileFormViewController.m
 @author 周益
 @version 1.0.0 2013/01/28 Creation
 Copyright (c) 2013年 mypocketbaby. All rights reserved.
 */

//  -业务逻辑细节说明-
//
//  @abstract       MobileFormViewController用于注册填写手机号码，或登录的找回密码。全局中的isRegisterOrNot，将与手机测试接口返回的status值（的1，2状态）做联合判断。
//              isRegistorOrNot=true（注册） && status=2（手机未注册） == true，就可以注册
//              isRegistorOrNot=false（找回密码） && status=1（手机已注册） == true，就可以找回密码
//

//  @discussion

//  @notes


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

#import "MobileFormViewController.h"
#import "Helper.h"
#import "AuthCodeFormViewController.h"
#import "Config.h"
#import "JMFBase.h"
#import "ServiceAgreementViewController.h"

@interface MobileFormViewController ()

@end

@implementation MobileFormViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //导航按钮：返回
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //手机号码textfield背景
    UIImageView *textFieldImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"com_bg_010"]];
    textFieldImageView.frame = CGRectMake(10, 20, 300, 45);
    [self.view addSubview:textFieldImageView];
    
    //输入框
    _textField = [Helper textField:CGRectMake(15, 21, 290, 40) byPlaceholder:_L(@"holder_16")];   //请输入手机号码
    _textField.keyboardType = UIKeyboardTypePhonePad;
    _textField.font = _SYS_FONT_007;
    _textField.borderStyle = UITextBorderStyleNone;
    [_textField becomeFirstResponder];
    [self.view addSubview:_textField];
    
    //服务协议
    _agreementLabel = [[RTLabel alloc] initWithFrame:CGRectMake(0.0f, _textField.frame.size.height + _textField.frame.origin.y + 20.0f, 320.0f, 30.0f)];
    _agreementLabel.font = _SYS_FONT_004;
    _agreementLabel.textAlignment = RTTextAlignmentCenter;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] init];
    
    [tapGestureRecognizer addTarget:self action:@selector(agreementAppearEvent:)];
    [_agreementLabel addGestureRecognizer:tapGestureRecognizer];
    
    _agreementLabel.text = _L(@"title_48");
    
    
    //发送按钮
    _sendButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 120, 300, 44)];
    [_sendButton setBackgroundImage:[UIImage imageNamed:@"com_btn_006_n"] forState:UIControlStateNormal];
    _sendButton.titleLabel.font = _SYS_FONT_009;
    [_sendButton setTitle:_L(@"btn_yes_17") forState:UIControlStateNormal];
    [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendButton addTarget:self action:@selector(sendButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_sendButton];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    [_textField resignFirstResponder];
}

#pragma mark - 自定义事件

/*!
 @abstract 返回按钮事件
 根据全局中的isRegisterOrNo来判断返回模式
 */
- (void)backButtonEvent:(id)sender
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isRegisterOrNot"]) {
        [self.navigationController dismissModalViewControllerAnimated:true];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/*!
 @abstract 发送按钮事件
 */
- (void)sendButtonEvent:(id)sender
{
    [_textField resignFirstResponder];
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_CHECK_EXIST];
    request.delegate = self;
    request.hudOn = true;;
    request.hudTitle = _L(@"title_loading_10");   //正在检查手机号码
    [request setValue:_textField.text forParameter:@"mobile"];
    [request asynchronous];
}

/*!
 @abstract 协议Label手势事件
 */
- (void)agreementAppearEvent:(id)sender
{
    ServiceAgreementViewController *serviceAgreementVC = [[ServiceAgreementViewController alloc] init];
    
    [self.navigationController pushViewController:serviceAgreementVC animated:YES];
}

#pragma mark - 私有方法

/*!
 @abstract 显示服务协议文字入口
 如果是注册时，那么就会被调用。
 */
- (void)agreementAppear
{
    [self.view addSubview:_agreementLabel];
    
    _sendButton.frame = CGRectMake(10, _agreementLabel.frame.origin.y + _agreementLabel.frame.size.height + 10.0f, 300, 44);
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)responseData
{
    
    //是否发送验证码的标记。
    //当全局isRegisterOrNot=true（是注册），status=2（手机未注册）时，值为true
    //当全局isRegisterOrNot=false（是找回密码），status=1（手机已注册）时，值为true
    BOOL sendCodeFlag = false;

    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    
    if (jmf.status == JMStatusSucceed) {
        
        //jmf成功时，表示此手机号码未被注册，可以注册或者不能更改密码
        
        //如果全局中，isRegisterOrNot=no，表示是更改密码，那么就要提示用户手机号码不存在
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isRegisterOrNot"] == NO) {
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_39")];   //手机不存在，请重新输入
        }
        //否则，可以注册
        else {
            sendCodeFlag = true;
        }
    }
    
    //jmf的status为2时，表示此手机号码被注册过，不可以注册或者能更改密码
    else if (jmf.status == 2) {
        
        //如果全局中，isRegisterOrNot=yes，表示是注册，那么就要提示用户
        
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"isRegisterOrNot"] == YES) {
            [Helper showAlertWithTitle:nil andMessage:_L(@"alert_40")];    //手机已被注册，请换一个
        }
        //否则，可以修改密码
        else {
            
            sendCodeFlag = true;
        }
        
        
    }
    else {

        [Helper easyShowJMFStatus:jmf];
    }
    
    
    //开始发送验证码
    if (sendCodeFlag) {
        
        //向服务器发送请求，获取验证码，并暂时保存手机号
        [[NSUserDefaults standardUserDefaults] setValue:_textField.text forKey:@"accountMobile"];
        
        //请求获取验证码
        JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_CODE];
        request.hudOn = true;
        request.hudTitle = _L(@"title_loading_11");
        request.delegate = self;
        [request setSuccessSelector:@selector(sendCodeEvent:)];
        [request setValue:_textField.text forParameter:@"mobile"];
        [request asynchronous];
    }
}

/*!
 @abstract 发送验证码请求成功事件
 会在发送验证码请求成功后被调用
 */
- (void)sendCodeEvent:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //获得成功后，跳转到填写验证码view
        AuthCodeFormViewController *authCodeFormVC = [[AuthCodeFormViewController alloc] init];
        
        [self.navigationController pushViewController:authCodeFormVC animated:YES];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}


//
- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:nil andMessage:_L(@"title_networkunavailabe")];
}

@end
